package com.simple.relaxed;

import com.simple.relaxed.anno.ScannerPackager;
import com.simple.relaxed.anno.impl.*;
import com.simple.relaxed.manager.impl.ConfigManager;
import com.simple.relaxed.utils.ReflectionsUtil;
import ohos.aafwk.ability.AbilityPackage;

import java.lang.reflect.InvocationTargetException;

/**
 * 此类为鸿蒙程序的主类，所有使用本框架的app，都需要继承自此类，否则框架的大部分功能，都将无法使用，并且出现一些不可控异常
 */
public class HarmonyApplication extends AbilityPackage {

    @Override
    public void onInitialize() {
        super.onInitialize();
        Class<? extends HarmonyApplication> aClass = this.getClass();
        // --------------初始化反射工具------------------
        ScannerPackager scannerPackager = aClass.getDeclaredAnnotation(ScannerPackager.class);
        String packageName;
        if (scannerPackager == null) {
            packageName = getBundleName();
        } else {
            packageName = scannerPackager.packageName();
        }
        ReflectionsUtil.init(this, packageName);
        // --------------全局对象注入--------------------
        try {
            ConfigImpl.configImpl(this);
            MarkImpl.initMark();
            InjectImpl.inject();
            EnhanceImpl.replaceProxy(this);
            AgentImpl.agentImpl(this);
            TaskClassImpl.taskClassImpl(this);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        InjectImpl.inject();
        try {
            SliceImpl.sliceImpl();
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重写此方法，定制程序关闭时，需要执行的事件
     */
    @Override
    public void onEnd() {
        super.onEnd();
        ConfigManager.getInstance().clear();
    }
}
